<template>
  <div>
    <div class="page-title">{{title}}</div>
    <div class="sectionCard" v-for="(item) in groups">
      <el-form label-position="left" :inline="true" label-width="100px">
        <div class="sectionTitle">{{ item.title }}</div>

        <el-row v-for="(child_item) in item.child">
          <el-form-item :label="child_item.label">
            <el-select v-if="child_item.type==2" v-model="child_item.value" style="width: 200px">
              <el-option
                  v-for="item_c in child_item.option"
                  :key="item_c.value"
                  :label="item_c.label"
                  :value="item_c.value"
              ></el-option>
            </el-select>
            <el-input v-else
                      :type="child_item.value_type=='number'?'number':'text'"
                      style="width: 200px"
                      clearable
                      v-model="child_item.value"
            />
          </el-form-item>
          <el-form-item>
            <el-tooltip
                class="box-item"
                effect="dark"
                content="mqtt未连接"
                placement="top"
                :disabled="!disabled"
            >
              <el-button type="primary" :disabled="disabled" @click="publish(item.topic,child_item.key,child_item.value,child_item.value_type)">
                下发指令
              </el-button>
            </el-tooltip>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>


</template>

<script setup>
import axios from "axios";
import {onMounted, ref,getCurrentInstance} from "vue";
const {proxy} = getCurrentInstance();
const route = useRoute();
import MQTT from "../mqtt/Mqtt";

let PublicMqtt = null;
/**
 * topic mqtt主题
 * title 组名称
 * value_type boolean，number,string
 * option 下拉框的下拉列表
 */
let groups = ref([])
const title = ref('指令下发页面')
const disabled = ref(false)
function publish(topic, key,value,valueType) {
  if(!topic||!key){
    proxy.$modal.msgWarning("请填写正确的参数");
    console.warn("请填写正确的参数......");
    return ;
  }
  if(typeof value!='boolean'&&!value){
    proxy.$modal.msgWarning("请输入值");
    return ;
  }
  if(valueType=='boolean'||valueType=='number'){
    try {
      value = JSON.parse(value)
    }catch (e){
      proxy.$modal.msgWarning("数据格式错误！");
      console.error('..........数据转换失败，异常信息',e)
      return ;
    }
  }
  let message = {[key]:value};
  console.log('..........发送指令',message)
  PublicMqtt.publish(topic, JSON.stringify(message),(error)=>{
    console.log('..msg',error)
    if(error==null){
      proxy.$modal.msgSuccess("指令下发成功！");
    }else {
      proxy.$modal.msgError("指令下发失败！");
    }

  })
}
 function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
onMounted(async () => {
  let page = getQueryString('page')
  if(!page){
    proxy.$modal.msgError("请传入页面参数");
    return;
  }
  axios.get('config/mqtt.json').then((res) => {
    const config = res.data;
    console.log('......config', config)
    PublicMqtt = new MQTT(config);//创建连接
    PublicMqtt.init();//初始化mqtt
  })
  try {
    const response = await axios.get(`page/${page}.json`);
    groups.value = response.data?.config||[];
    title.value = response.data?.title||'指令下发页面';
  } catch (error) {
    console.error('Failed to load page:', page);
    proxy.$modal.msgError("页面"+page+"不存在！");
  }
  PublicMqtt.getClient().on('error', () => {
    disabled.value = true;
  });
  PublicMqtt.getClient().on('success', () => {
    disabled.value = false;
  });
})

</script>

<style lang="scss" scoped>
.page-title{
  font-size: 20px;
  font-weight: 600;
  padding-left: 18px;
  padding-top: 18px;
  padding-bottom: 18px;
}
</style>